# coding:utf8
import copy

from sqlalchemy import or_

from appserver import db_store
from models.entity.device_with_sensor import DeviceWithSensor
from models.entity.model_base import ModelBase
import uuid

"""
传感器表
"""


class Sensor(ModelBase):
    __tablename__ = "sensors"
    __bind_key__ = "main"

    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')
    code = db_store.Column(db_store.String(64), nullable=False, unique=True, comment=u"GUID")
    name = db_store.Column(db_store.String(64), nullable=False, unique=True, comment=u'传感器名称')
    description = db_store.Column(db_store.String(255), nullable=True, comment=u"描述")
    #
    address = db_store.Column(db_store.String(255), nullable=True, comment=u"原始地址")
    tag_type = db_store.Column(db_store.String(255), nullable=True, comment=u"标签类型") # io ,memory
    client_access = db_store.Column(db_store.String(255), nullable=True, comment=u"客户访问权限") # r, rw
    scan_rate = db_store.Column(db_store.Integer, nullable=True, comment=u"扫描周期")
    #

    sensor_type_id = db_store.Column(db_store.Integer, db_store.ForeignKey('sensor_types.id'), nullable=False,
                                     comment=u"传感器分类ID")
    sensor_group_id = db_store.Column(db_store.Integer, db_store.ForeignKey("sensor_groups.id"),comment=u"传感器分组id")
    icon = db_store.Column(db_store.String(32), comment="图标")
    dis_order = db_store.Column(db_store.Integer, comment=u"排序",default=0)
    # 以下的字段是新加的
    eng_unit = db_store.Column(db_store.String(10), comment=u"工程单位")
    data_type = db_store.Column(db_store.String(32),comment=u"数据类型")
    # data_type的值:boolean, int16 ,int32, in64 ,float
    #       boolean
    #       WORD             INT16
    #       DWORD          INT32
    #       FLOAT             浮点数
    #       DOUBLE         双精度浮点数
    #       STRING           字符串
    #       LONG               长整数
    #       LOCATION      经纬度
    
    # 新加的字段结束，以下的字段是需要修改的
    # 预警上下限
    al_h = db_store.Column(db_store.Float,  comment=u"预警上限")
    al_l = db_store.Column(db_store.Float, comment=u"预警下限")
    # 报警上下限
    al_hh = db_store.Column(db_store.Float,  comment=u"报警上限")
    al_ll = db_store.Column(db_store.Float, comment=u"报警下限")
    # 工程上下限
    eng_max  = db_store.Column(db_store.Float,  comment=u"工程上限")
    eng_min  = db_store.Column(db_store.Float, comment=u"工程下限")
    # 远程服务器相关
    topic = db_store.Column(db_store.String(255), comment=u"MQTT topic")
    client_id = db_store.Column(db_store.String(64),comment=u"MQTT client id")  # 网关id
    # remote_host_id = db_store.Column(db_store.Integer,db_store.ForeignKey("remote_hosts.id"),comment=u"远程服务器信息")
    # 说明结束
    status = db_store.Column(db_store.Integer, comment=u"状态", default=0)  # 1-正常 0-禁用
    # 传感器值表达式
    is_exp = db_store.Column(db_store.Integer,comment=u"是否存在表达式",default=0)  # 0-无 1-有
    exp = db_store.Column(db_store.String(255),comment=u"表达式")
    alarm = db_store.Column(db_store.Integer, comment=u"状态", default=0)  # 1-报警 0-不报警

    def __repr__(self):
        return "<Sensor %s>" % self.name

    def from_dict(self, rev_source):
        source = copy.deepcopy(rev_source)
        # print('source', source)
        # if "parent_id" in source:
        #     source["parent_id"] = source.pop("parent_id")
        # if "level" in source:
        #     source["depth"] = source.pop("level")
        # if "children" in source:
        #     source.pop("children")
        # ******因为facility模型中没有district_id这个字段所以要pop掉
        # if "district_id" in source:
        #     source.pop('district_id')
        for k in source:
            # print('k',k)
            try:
                getattr(self, k)
                # print('getattr',getattr(self, k))
            except AttributeError as e:
                print(e)
                raise RuntimeError("数据格式错误")
            setattr(self, k, source[k])
            # print('setattr',setattr(self, k, source[k]))

    def save(self):

        if self.id is None:
            self.id = self.get_max_id() + 1
        try:
            # if self.id is None:
            #     self.id = self.get_max_id() + 1
            # if self.code is None:
            #     self.code = uuid.uuid4().hex
            db_store.session.add(self)
            db_store.session.commit()
            return True
        except Exception as e:
            print(e)
            db_store.session.rollback()
            return False

    @staticmethod
    def get_all_sensors():
        return Sensor.query.all()


    @staticmethod
    def get_sensor_by_id(id):
        return Sensor.query.filter_by(id=id).first()

    @staticmethod
    def get_sensor_by_topic(topic):
        return Sensor.query.filter_by(topic=topic).first()

    @staticmethod
    def get_sensor_by_name(name):
        return Sensor.query.filter_by(name=name).first()

    @staticmethod
    def get_sensor_by_code(code):
        return Sensor.query.filter_by(code=code).first()

    @staticmethod
    def get_sensors_by_device_id(device_id):
        rlist=[]
        connectors=DeviceWithSensor.query.filter_by(device_id=device_id).all()
        for item in connectors:
            rlist.append(Sensor.query.filter_by(id=item.sensor_id).first())
        return rlist

    @staticmethod
    def search(query_word):
        tmp = {}
        data = []
        sensors = Sensor.query.filter(
            or_(Sensor.code.like('%' + query_word + '%'), Sensor.name.like('%' + query_word + '%'),
                Sensor.description.like('%' + query_word + '%'), Sensor.topic.like('%' + query_word + '%'),
                Sensor.sensor_type_id.like('%' + query_word + '%'))).all()
        for obj in sensors:
            data.append(obj.to_dict())
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return tmp
    """
    @staticmethod
    def search(query_word):
        data = []
        devices = Device.query.filter(
            or_(Device.code.like('%' + query_word + '%'), Device.name.like('%' + query_word + '%'),
                Device.description.like('%' + query_word + '%'))).all()
        for obj in devices:
            data.append(obj.to_dict())
        return data
    """
